//动态加载路由的模块
import fs from 'fs';
import {fileURLToPath} from 'url';
import {dirname} from 'path';

//获取文件路径
export function WFileName(url){
    let filename = fileURLToPath(url);
    return filename;
}
//获取文件所在的目录路径
export function dirName(url){
    let filename = WFileName(url);
    let d_name = dirname(filename);
    return d_name
}
//从文件路径中获取文件名
export function getFileName(filePath){
    let arr = filePath.split('\\');
    let tmparr = arr[arr.length-1];
    let tmpName = tmparr.split('.');
    let fileName = tmpName[0];
    return fileName;
}
//查找指定目录下的所有js文件，并返回文件列表
export function findRouter(path){
    let curPath = path || './controllers';
    let allFile = fs.readdirSync(curPath);
    let files = allFile.filter((f)=>{return f.endsWith('.js')});
    console.log(files);
    return files;
}
//遍历js文件，加载路由
export function reqRouter(files,router){
    let curPath = '../controllers';
    files.forEach(async file =>{
        let filePath = `${curPath}/${file}`;
        //使用import函数动态导入模块
        let tmpModule = await import(filePath);
        let tmpObj = tmpModule.default;
        for(let item in tmpObj){
            let tmpArr = item.split(' ');
            let method = tmpArr[0];
            let path = tmpArr[1];
            let fn = tmpObj[item];
            //路由处理函数的命名规则是"[HTTP方法] [路径] : [处理函数]"
            router[method](path,fn);
        }
    })
}

